package com.example.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.Course;
import com.example.entity.Score;
import com.example.entity.Student;
import com.example.entity.Teacher;
import com.example.exception.CustomException;
import com.example.mapper.CourseMapper;
import com.example.mapper.ScoreMapper;
import com.example.mapper.StudentMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 成绩信息表业务处理
 **/
@Service
public class ScoreService {

    @Resource
    private ScoreMapper scoreMapper;
    @Resource
    private CourseMapper courseMapper;
    @Resource
    private StudentMapper studentMapper;

    /**
     * 新增
     */
    public void add(Score score) {
        // 判断下该门课该学生 有没有录入过成绩，如果有就不需要在录入了
        Score dbScore = scoreMapper.selectByCourceIdAndStudentId(score.getCourseId(), score.getStudentId());
        if (ObjectUtil.isNotEmpty(dbScore)) {
            throw new CustomException(ResultCodeEnum.SCORE_ALREADY_ERROR);
        }
        // 计算一下总成绩
        double total = score.getOrdinaryScore() * 0.3 + score.getExamScore() * 0.7;
        score.setScore(total);
        scoreMapper.insert(score);

        // 录入之后，及格的学生需要获取对应的学分
        if (total >= 60) {
            Course course = courseMapper.selectById(score.getCourseId());
            Student student = studentMapper.selectById(score.getStudentId());
            student.setScore(student.getScore() + course.getScore());
            studentMapper.updateById(student);
        }
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        Score score = scoreMapper.selectById(id);
        scoreMapper.deleteById(id);
        // 扣除学生对应的学分
        Student student = studentMapper.selectById(score.getStudentId());
        Course course = courseMapper.selectById(score.getCourseId());
        student.setScore(student.getScore() - course.getScore());
        studentMapper.updateById(student);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        // 使用 Java 21 增强的 Stream API
        ids.forEach(scoreMapper::deleteById);
    }
    /**
     * 修改
     */
    public void updateById(Score score) {
        scoreMapper.updateById(score);
    }

    /**
     * 根据ID查询
     */
    public Score selectById(Integer id) {
        return scoreMapper.selectById(id);
    }

    /**
     * 查询所有
     * 添加权限控制：学生只能查看自己的成绩，教师只能查看自己教授课程的成绩
     */
    public List<Score> selectAll(Score score) {
        List<Score> list = scoreMapper.selectAll(score);
        
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            return list;
        }
        
        // 根据角色过滤成绩数据
        return switch (currentUser.getRole()) {
            case "STUDENT" -> {
                // 学生只能看到自己的成绩
                Student student = (Student) currentUser;
                yield list.stream()
                        .filter(s -> s.getStudentId().equals(student.getId()))
                        .collect(Collectors.toList());
            }
            case "TEACHER" -> {
                // 教师只能看到自己教授课程的学生成绩
                Teacher teacher = (Teacher) currentUser;
                yield list.stream()
                        .filter(s -> s.getTeacherId().equals(teacher.getId()))
                        .collect(Collectors.toList());
            }
            default -> list; // 管理员可以看到所有成绩
        };
    }

    /**
     * 分页查询
     * 添加权限控制：学生只能查看自己的成绩，教师只能查看自己教授课程的成绩
     */
    public PageInfo<Score> selectPage(Score score, Integer pageNum, Integer pageSize) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser != null) {
            switch (currentUser.getRole()) {
                case "STUDENT" -> {
                    // 学生只能看到自己的成绩
                    Student student = (Student) currentUser;
                    score.setStudentId(student.getId());
                }
                case "TEACHER" -> {
                    // 教师只能看到自己教授课程的学生成绩
                    Teacher teacher = (Teacher) currentUser;
                    score.setTeacherId(teacher.getId());
                }
                // 管理员不做限制
            }
        }
        
        PageHelper.startPage(pageNum, pageSize);
        List<Score> list = scoreMapper.selectAll(score);
        return PageInfo.of(list);
    }

}
